package com.zyzd.commontools;

import android.app.Application;
import android.content.Context;
import android.os.Looper;

import com.zyzd.commontools.utils.LogUtils;

/**
 * Created by 李宗源 on 2019/1/14.
 */

public class AppContext {

    private static final Application sApplication;

    static {
        Application app = null;
        try {
            app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
            if (app == null)
                throw new IllegalStateException("Static initialization of Applications must be on main thread.");
        } catch (final Exception e) {
            LogUtils.e("Failed to get current application from AppGlobals." + e.getMessage());
            try {
                app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
            } catch (final Exception ex) {
                LogUtils.e("Failed to get current application from ActivityThread." + e.getMessage());
            }
        } finally {
            sApplication = app;
        }
    }

    private static void checkAppContext() {
        if (sApplication == null)
            throw new IllegalStateException("app reference is null");
    }

    public static Context getContext() {
        checkAppContext();
        return sApplication.getApplicationContext();
    }

    public static boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
}
